<?php

namespace common\models;

use Yii;
use common\extended\system\Util;

/**
 * This is the model class for table "sys_user".
 *
 * @property string $uid
 * @property string $login_name
 * @property string $user_name
 * @property string $password
 * @property string $user_role
 * @property integer $status
 * @property string $mobile
 * @property string $address
 * @property integer $user_type
 * @property string $create_time
 * @property string $create_uid
 * @property string $create_name
 * @property string $remark
 */
class SysUser extends \yii\db\ActiveRecord
{
	/**
	 * 可以登录
	 * @var integer
	 */
	const NORMAL = 1;
	/**
	 * 不能登录
	 * @var integer
	 */
	const DISABLE = 0;
	/**
	 * 删除
	 * @var integer
	 */
	const DELETE = -1;
    /**
     * @inheritdoc
     */

    public $newPassword; // 修改密码时的新密码
    public $oldNewPassword; // 确认新密码
    public $errorMessage; // 错误信息

    public static function tableName()
    {
        return 'sys_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'address'], 'required', 'on' => ['addAgent']],
            ['mobile', 'validateMobile', 'on' => ['addAgent']],
            [['user_name'], 'required', 'message' => '代理商名称不能为空', 'on' => ['addAgent']],

            [['login_name'], 'unique', 'message' => '登录名已被占用', 'on' => ['addAgent']],

            [['login_name', 'password', 'user_role', 'user_type', 'newPassword', 'oldNewPassword'], 'required', 'on' => ['login', 'editPass', 'addAgent']],
            [['user_role', 'status', 'user_type', 'create_uid'], 'integer'],
            [['create_time'], 'safe'],
            [['create_time'], 'default', 'value' => function () { return date('Y-m-d H:i:s'); }],
            [['login_name', 'user_name', 'password', 'mobile', 'address', 'create_name', 'remark'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'uid' => '主键',
            'login_name' => '用户登录名（手机号码 ）',
            'user_name' => '用户名称',
            'password' => '登录密码',
            'user_role' => '用户角色',
            'status' => '用户状态（1：可以登录 0：不能登录  -1：删除）',
            'mobile' => '联系电话',
            'address' => '联系住址',
            'user_type' => '用户类型（1：系统 2：代理商 3：老板 4：店长）',
            'create_time' => '创建时间',
            'create_uid' => '创建人编号',
            'create_name' => '创建人登录名',
            'remark' => '备注',
            'newPassword' => '新密码',
            'oldNewPassword' => '确认密码',
        ];
    }

    public function getAgents()
    {
        return $this->hasOne(SysAgent::className(), ['agent_uid' => 'uid']);
    }

    public function scenarios()
    {
        return [
            'login' => ['login_name', 'password'],
            'editPass' => ['password', 'newPassword', 'oldNewPassword'],
            'addAgent' => ['login_name', 'password', 'user_name', 'mobile', 'address', 'user_role', 'user_type', 'create_time'],
            'editAgent' => ['login_name', 'user_name', 'mobile', 'address', 'user_role', 'user_type'],
        ];
    }

    /**
     * 登陆
     * @return bool
     */
    public function login()
    {
        /*if (!$this->validate()) {
            return false;
        }*/

        if (empty($this->login_name)) {
            $this->addError('login_name', '请输入账户名！');
            return false;
        }
        if (empty($this->password)) {
            $this->addError('password', '请输入密码！');
            return false;
        }

        if (!($info = self::findOne(['login_name' => $this->login_name]))) {
            $this->addError('login_name', '该用户不存在，请联系管理员！');
            return false;
        }

        if (!$this->validatePassword($info->password)) {
            $this->addError('password', '用户名或密码错误，请重新输入！');
            return false;
        }

        if ($info->status != self::NORMAL) {
            $this->addError('login_name', '该用户不存在，请联系管理员！');
            return false;
        }

        $session = Yii::$app->session;
        $session->set('username', $info->login_name);
        $session->set('userpass', $info->password);
        $session->set('userid', $info->uid);
        // 用户类型为老板
        if ($info->user_type == 3 && ($SysShop = \common\models\SysShop::findOne(['boss_uid' => $info->uid]))) {
            $session->set('shopId', $SysShop->shop_id);
        }

        // 记录日志
        $this->addLog([
            'user_uid' => $info->uid,
            'login_name' => $info->login_name,
            'ip' => Yii::$app->request->userIP,
            'controller_name' => 'public',
            'method_name' => 'login',
            'info' => '登陆了系统',
            'date_created' => date('Y-m-d H:i:s'),
            'log_type' => 1
        ]);

        return true;
    }

    /**
     * 修改密码
     * @return bool
     */
    public function editPassword()
    {
        /*if (!$this->validate()) {
            return false;
        }*/

        if (empty($this->password)) {
            $this->addError('password', '请输入原密码！');
            return false;
        }
        if (empty($this->newPassword)) {
            $this->addError('password', '请输入新密码！');
            return false;
        }
        if (empty($this->password)) {
            $this->addError('password', '请输入密码确认！');
            return false;
        }
        if ($this->newPassword != $this->oldNewPassword) {
            $this->addError('password', '两次输入的密码不一致，请重新输入！');
            return false;
        }
        $uid = Yii::$app->session->get('userid');
        if (!($info = self::findOne($uid))) {
            $this->addError('password', '该用户不存在，请联系管理员！');
            return false;
        }
        if (!$this->validatePassword($info->password)) {
            $this->addError('password', '请输入正确的原密码！');
            return false;
        }
        $password = Util::strEncryption($this->newPassword);
        if (self::updateAll(['password' => $password], ['uid' => $uid]) === false) {
            return false;
        } else {
            Yii::$app->session->set('userpass', $password);
            return true;
        }
    }

    /**
     * 验证密码
     * @param $password
     * @return bool
     */
    protected function validatePassword($password)
    {
        return Util::strEncryption($this->password) === $password;
    }

    /**
     * 检查手机号码格式
     * @param $attribute
     * @param $params
     */
    public function validateMobile($attribute, $params)
    {
        if (!preg_match("/^1\d{10}$/", $this->mobile)) {
            $this->addError($attribute, '请输入正确的手机号！');
        }
    }

    /**
     * 记录日志
     * @param array $data 日志数据
     */
    protected function addLog($data)
    {
        Yii::$app->db->createCommand()->insert('sys_log', $data)->execute();
    }

    /**
     * 修改一个用户的状态
     * @param $uid
     * @param int $status [-1, 0, 1]
     * @return bool|int
     */
    public function setStatus($uid, $status = 1)
    {
        if (in_array($status, [-1, 0, 1])) {
            return Yii::$app->db->createCommand()->update('sys_user', ['status' => $status], ['uid' => $uid])->execute();
        } else {
            return false;
        }
    }

    /**
     * 检查新增/编辑代理商的账号信息
     * @return boolean
     */
    public function checkParamAgent()
    {
        if (empty($this->login_name)) {
            $this->errorMessage = '请输入账户名称！';
            return false;
        }
        if (empty($this->password) && empty($this->uid)) {
            $this->errorMessage = '请输入账户密码！';
            return false;
        }
        if (empty($this->mobile)) {
            $this->errorMessage = '请输入联系电话！';
            return false;
        }
        if (!\common\extended\system\Util::checkMobile($this->mobile)) {
            $this->errorMessage = '请输入正确的联系电话！';
            return false;
        }
        if (empty($this->user_name)) {
            $this->errorMessage = '请输入代理商名称！';
            return false;
        }
        if (empty($this->address)) {
            $this->errorMessage = '请输入通讯地址！';
            return false;
        }

        if ($this->uid) {
            $isLoginNameUnique = self::findOne("login_name = '{$this->login_name}' AND uid != {$this->uid}");
        } else {
            $isLoginNameUnique = self::findOne(['login_name' => $this->login_name]);
        }
        if ($isLoginNameUnique) {
            $this->errorMessage = '该账户名称已注册，请重新输入！';
            return false;
        }
        return true;
    }
}
